package com.party.mobile.web.controller.wechat;

import com.party.api.service.wechatPlatform.IWechatPlatformService;
import com.party.common.constant.WechatConstant;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.wechat.WechatMerchants;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.wechat.IWechatMerchantsService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.core.service.wechatPlatform.IWechatOpenPlatformService;
import com.party.mobile.biz.wechat.WechatBizService;
import com.party.mobile.biz.wechat.WechatPayBizService;
import com.party.mobile.biz.wechatPlatform.WechatPlatformBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.wechat.input.AccessTokenResponse;
import com.party.mobile.web.dto.wechat.input.GetsignkeyResponse;
import com.party.mobile.web.dto.wechat.output.GetsignkeyRequest;
import com.party.mobile.web.utils.VerifyCodeUtils;
import com.party.mobile.web.utils.WechatPayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;

/**
 * Created by wei.li
 *
 * @date 2017/8/26 0026
 * @time 15:23
 */

@Controller
@RequestMapping(value = "wechat/test")
public class WechatTestController {

    @Autowired
    private IWechatPlatformService wechatPlatformService;

    @Autowired
    private WechatPlatformBizService wechatPlatformBizService;

    @Autowired
    private IWechatOpenPlatformService wechatOpenPlatformService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private WechatBizService wechatBizService;


    @Value("#{wechat_platform['wechat.platform.appId']}")
    private String componentAppid;

    @Autowired
    private WechatPayBizService wechatPayBizService;

    @Autowired
    private IWechatMerchantsService wechatMerchantsService;

    protected static Logger logger = LoggerFactory.getLogger(WechatTestController.class);

  /*  @ResponseBody
    @RequestMapping(value = "getOauth2Url")
    public AjaxResult getOauth2Url(String redirectUrl){
        AjaxResult ajaxResult = new AjaxResult();
        WechatOpenMember wechatOpenMember = wechatOpenMemberService.list(new WechatOpenMember()).get(0);
        try {
            String url = wechatPlatformBizService.getOauth2Url(redirectUrl, wechatOpenMember.getAuthorizerAppid());
            logger.info("授权url{}", url);
            ajaxResult.setData(url);
            ajaxResult.setSuccess(true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ajaxResult;
    }


    @ResponseBody
    @RequestMapping(value = "getOpenId")
    public AjaxResult getOpenId(String code){
        logger.info("授权回来的code{}", code);
        WechatOpenMember wechatOpenMember = wechatOpenMemberService.list(new WechatOpenMember()).get(0);
        WechatOpenPlatform wechatOpenPlatform = wechatOpenPlatformService.list(new WechatOpenPlatform()).get(0);
        Oauth2AccessTokenResponse oauth2AccessTokenResponse
                = wechatPlatformService.getOauth2AccessToken(wechatOpenMember.getAuthorizerAppid(), code,
                componentAppid , wechatOpenPlatform.getComponentAccessToken());
        logger.info("网页授权获取token{}", oauth2AccessTokenResponse.toString());

        UserInfoResponse userInfoResponse
                = wechatBizService.userInfo(oauth2AccessTokenResponse.getOpenid(), oauth2AccessTokenResponse.getAccessToken());
        logger.info("获取用户信息{}", userInfoResponse);
        return AjaxResult.success();
    }*/

    @ResponseBody
    @RequestMapping(value = "getOauth2Url")
    public AjaxResult getOauth2Url(String redirectUrl) throws UnsupportedEncodingException {
        String url = wechatBizService.getOathorizeUrl(redirectUrl);

        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setData(url);
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping(value = "getOpenId")
    public AjaxResult getOpenId(String code){
        AccessTokenResponse accessTokenResponse = wechatBizService.acccessToken(code, new MemberGroup());
        WechatOpenMember wechatOpenMember = wechatOpenMemberService.getSystem();
        wechatBizService.info(accessTokenResponse.getOpenid(), wechatOpenMember.getAuthorizerAccessToken());
        return AjaxResult.success();
    }


    /**
     * 微信支付沙盒环境（微信根证书验证）
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "getsignkey")
    public AjaxResult getsignkey(){
        AjaxResult ajaxResult = new AjaxResult();
        WechatMerchants wechatMerchantsSystem = wechatMerchantsService.getSystem();
        String nonceStr = VerifyCodeUtils.RandomString(WechatConstant.RANDOM_LENGTH);
        GetsignkeyRequest request = new GetsignkeyRequest();
        request.setMchId(wechatMerchantsSystem.getMerchantId());
        request.setNonceStr(nonceStr);
        String sign = WechatPayUtils.getSign(request, wechatMerchantsSystem.getMerchantApiKey().trim());
        request.setSign(sign);
        GetsignkeyResponse response = wechatPayBizService.getsignkey(request);
        ajaxResult.setData(response);
        return ajaxResult;
    }
}
